package two.marks;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
public class Tracker extends Service implements LocationListener 
{
  
    private boolean isGPSEnabled = false;
    private boolean isNetworkEnabled = false;
   // private boolean isGPSRdy=false;
    private boolean isWIFIRdy=false;
    private boolean canGetLocation = false;    
   
    private Context mContext;
    private TextView textViewCoords;
    private TextView textViewStatus;
    private TextView textViewPhone;
    private Button buttonRefesh;
    private Button buttonStop;
    
    private Location location; 
    private ConnectivityManager connManager;

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; 
    private static final long MIN_TIME_BW_UPDATES = 0;
 
    protected LocationManager locationManager;
 
    public Tracker(Context context) 
    {   
    	this.mContext = context;
    	
    	this.textViewCoords=  (TextView) ((Activity) this.mContext).findViewById(R.id.coordinates);
    	this.textViewPhone=(TextView)((Activity) this.mContext).findViewById(R.id.phone);
    	this.textViewStatus=  (TextView) ((Activity) this.mContext).findViewById(R.id.status);
    	
    	this.buttonRefesh=  (Button)((Activity) this.mContext).findViewById(R.id.refresh);
    	this.buttonStop=  (Button)((Activity) this.mContext).findViewById(R.id.stop);
    	
    	this.textViewPhone.setText(((TelephonyManager)this.mContext.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId());
    	this.textViewCoords.setText("obteniendo coordenadas");
    	this.textViewStatus.setText("Iniciando recursos");
 	
    	
    	this.buttonRefesh.setOnClickListener(new View.OnClickListener() 
    	{
    		public void onClick(View v) 
    		{
    			textViewCoords.setText("obteniendo coordenadas");
    			buttonRefesh.setEnabled(false);
    			start();
    		}
    	});
    	this.buttonRefesh.setEnabled(false);
    	
    	
    	this.buttonStop.setOnClickListener(new View.OnClickListener() 
    	{
    		public void onClick(View v) 
    		{
    			stop();
    		}
    	});
    	
    }
    
    
    public void start()
    {
    	this.stop();
    	this.locationManager = (LocationManager) this.mContext.getSystemService(LOCATION_SERVICE);
    	
    	this.textViewCoords.setText("obteniendo coordenadas");
    	this.textViewStatus.setText("Iniciando recursos");
    	this.textViewPhone.setText(((TelephonyManager)this.mContext.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId());
        
    	this.buttonRefesh.setEnabled(false);
    	
    	if(this.check())
    		this.getLocation();
    }
    public void stop()
    {
    	if(locationManager!= null)
        {
            locationManager.removeUpdates(Tracker.this);
            
        }
    	this.textViewCoords.setText("- - -");
    	this.textViewStatus.setText("- - -");
    	this.textViewPhone.setText("- - -");
    	this.buttonRefesh.setEnabled(true);
    	
    }
    
    public boolean check()
	{
    	this.canGetLocation=true;
    	try 
    	{
    		
    		this.isGPSEnabled = this.locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    		this.isNetworkEnabled = this.locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
               
    		this.connManager = (ConnectivityManager) this.mContext.getSystemService(CONNECTIVITY_SERVICE);
    		this.isWIFIRdy=this.connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();

    		if (!this.isGPSEnabled || !this.isNetworkEnabled) 
    		{
    			this.canGetLocation= false;
    			this.textViewCoords.setText("- - -");
    			this.textViewStatus.setText("se debe activar ubicacion wifi y gps\n Presione el boton refrescar para volver a intentarlo");
              	this.showLocationManagerAlert();    	
    		} 
    		if(!isWIFIRdy)
    		{
    			this.canGetLocation= false;
    			this.textViewCoords.setText("- - -");
    			this.textViewStatus.setText("se debe activar red wifi\n Presione el boton refrescar para volver a intentarlo");
              	this.showConnectivityManagerAlert(); 	
    		}
    	}
    	catch (Exception e) 
    	{
    		e.printStackTrace();
    		this.textViewCoords.setText("- - -");
    		this.textViewStatus.setText(e.getMessage());
    	}
    	
    	return this.canGetLocation;
    	
    }
    
    private void showLocationManagerAlert()
    {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this.mContext);
        alertDialog.setTitle("Ubicacion por GPS y WIFI");
        alertDialog.setMessage("Debe activar la ubicacion por wifi y gps");
        
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() 
    								{
    									public void onClick(DialogInterface dialog,int which) 
    									{
							                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							                mContext.startActivity(intent);
    									}
    								});

        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
        							{
							            public void onClick(DialogInterface dialog, int which) 
							            {
								            dialog.cancel();
								            getLocation();
							            }
        							});
        
        
        
        this.textViewStatus.setText("Presione refrescar para volver a intentarlo");
        this.buttonRefesh.setEnabled(true);
        alertDialog.show();
  
    }
    private void showConnectivityManagerAlert()
    {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        alertDialog.setTitle("Activar WIFI");
        alertDialog.setMessage("Para funcionar correctamente debe conectarse a una red WIFI");
        
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() 
									{
										public void onClick(DialogInterface dialog,int which) 
										{
							                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
							                mContext.startActivity(intent);
										}
									});

		alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
									{
							            public void onClick(DialogInterface dialog, int which) 
							            {
								            dialog.cancel();
								            getLocation();
							            }
									});
		alertDialog.show();
		this.buttonRefesh.setEnabled(true);
		
    }
    
    public Location getLocation()
    {
    	try 
    	{
    		if(this.canGetLocation)
    		{
    			if (this.isNetworkEnabled) 
                {
    				this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                  
    				Log.d("Network", "Network");
                
                    if (this.locationManager != null) 
                    {
                    	this.location = this.locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (this.location != null) 
                        {
                        	this.textViewCoords.setText( Double.toString(location.getLatitude()) +" , "+ Double.toString(location.getLongitude()));
                        	this.textViewStatus.setText("ubicado mediante network");
                        }
                    }
                }
     
                if (this.isGPSEnabled) 
                {
                    if (this.location == null) 
                    {
                    	this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        
                        Log.d("GPS Enabled", "GPS Enabled");
                        
                        if (this.locationManager != null) 
                        {
                        	this.location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) 
                            {
                            	this.textViewCoords.setText( Double.toString(location.getLatitude()) +" , "+ Double.toString(location.getLongitude()));
                            	this.textViewStatus.setText("ubicado mediante gps");
                            }
                        }
                    }
                }
    		}
    		else
    		{
    	
    		}
    		
    	}
    	catch (Exception e) 
    	{
    		e.printStackTrace();
    		this.textViewCoords.setText("- - -");
    		this.textViewStatus.setText(e.getMessage());
    	}
    	return this.location;
    	
    }
 

 
    @Override
    public void onLocationChanged(Location locationc) 
    {
    	
    	Log.d("location", Double.toString(locationc.getLatitude()) +" , "+ Double.toString(locationc.getLongitude()));
    	this.textViewCoords.setText( Double.toString(locationc.getLatitude()) +" , "+ Double.toString(locationc.getLongitude()));
    }
 
    @Override
    public void onProviderDisabled(String provider) 
    {
    	this.textViewCoords.setText("provider disabled");
    	start();
    }
 
    @Override
    public void onProviderEnabled(String provider) 
    {
    	this.textViewCoords.setText("provider enabled");
    	start();
    }
 
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) 
    {
    	this.textViewCoords.setText("onStatusChanged");
    	start();
    }
 
    @Override
    public IBinder onBind(Intent arg0) 
    {
        return null;
    }
 
}